package cn.bugDance.domain.strategy.service;

import cn.bugDance.domain.activity.model.entity.ActivityEntity;
import cn.bugDance.domain.activity.repository.IActivityRepository;
import cn.bugDance.domain.strategy.model.entity.RuleConfigEntity;
import cn.bugDance.domain.strategy.model.entity.StrategyAwardEntity;
import cn.bugDance.domain.strategy.model.valobj.RuleWeightVO;
import cn.bugDance.domain.strategy.model.valobj.StrategyConstant;
import cn.bugDance.domain.strategy.model.valobj.StrategyDelayJobQueueData;
import cn.bugDance.domain.strategy.repository.IStrategyRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.event.ListDataEvent;
import java.util.*;

@Service
@Component
public class StrategyQuotaService implements IStrategyQuotaService{

    @Resource
    private IStrategyRepository strategyRepository;
    @Resource
    private IActivityRepository activityRepository;


    @Override
    public StrategyDelayJobQueueData takeStrategyJobQueue() {
        return strategyRepository.takeStrategyJobQueue();
    }

    @Override
    public void strategyAwardSubtractQuota(StrategyDelayJobQueueData strategyDelayJobQueueData) {
        Long strategyId = strategyDelayJobQueueData.getStrategyId();
        Integer awardId = strategyDelayJobQueueData.getAwardId();

        strategyRepository.strategyAwardSubtractionQuotaDataBase(strategyId, awardId);
    }

    @Override
    public List<RuleWeightVO> queryStrategyRuleWeight(Long activityId) {
        ActivityEntity activityEntity = activityRepository.queryActivityByActivityId(activityId);
        Long strategyId = activityEntity.getStrategyId();
        RuleConfigEntity ruleConfigEntity = strategyRepository.queryRuleConfigRule(strategyId, StrategyConstant.StrategyRule.RULE_WEIGHT);

        Map<Integer, List<Integer>> ruleConfigSplit = ruleConfigEntity.ruleConfigSplit();
        Set<Integer> weights = ruleConfigSplit.keySet();

        List<RuleWeightVO> ruleWeightVOS = new ArrayList<>();
        for (Integer weight : weights) {
            RuleWeightVO ruleWeightVO = new RuleWeightVO();
            List<Integer> awardIds = ruleConfigSplit.get(weight);
            List<RuleWeightVO.Award> ruleWeightVOAwards = new ArrayList<>();
            for (Integer awardId : awardIds) {
                RuleWeightVO.Award ruleWeightVOAward = new RuleWeightVO.Award();
                StrategyAwardEntity strategyAwardEntity = strategyRepository.queryStrategyAwardByStrategyIdAndAwardId(strategyId, awardId);

                ruleWeightVOAward.setAwardId(awardId);
                ruleWeightVOAward.setAwardTitle(strategyAwardEntity.getAwardTitle());
                ruleWeightVOAwards.add(ruleWeightVOAward);
            }
            ruleWeightVO.setWeight(weight);
            ruleWeightVO.setAwardList(ruleWeightVOAwards);
            ruleWeightVOS.add(ruleWeightVO);
        }
        return ruleWeightVOS;
    }
}
